package com.wyiot.core.config;

import com.alibaba.fastjson.JSON;
import com.wyiot.core.utils.R;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 *r类同一封装返回配置列（aop）
 * @author yly
 * @since 2022年03月31日
 */
@ControllerAdvice//(basePackages = "com.wyiot.pet.controller")
public class ResultResponseHandler implements ResponseBodyAdvice<Object> {
    /**
     * 是否支持advice功能 true为支持
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;//true为开启通知
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (o instanceof String){
            return JSON.toJSON(R.ok(o));
        }else if (o instanceof R){
            return o;
        }
        return R.ok(o);
    }
}
